<template>
	<view class="fee_main">
		<view class="fee_main_bgBox">
			<uni-forms ref="formRef" label-width="150" :model="orderFeeVo">
				<view
					class="item_fee"
					v-for="(item, index) in orderFeeVo.orderFeeDetailVos"
					:key="index"
				>
					<view class="item_fee_tableHead">
						<view
							class="item_fee_tableHead_left"
							@click="item.isShow = !item.isShow"
						>
							<span :class="item.isShow ? 'down_up_' : 'down_up'"></span>
							费用{{ index + 1 }}
						</view>
						<uni-icons
							@click="deleteFun(index)"
							v-if="orderFeeVo.orderFeeDetailVos.length == 1 ? false : true"
							type="minus-filled"
							color=" rgba(245, 108, 108, 1)"
							size="24"
						></uni-icons>
					</view>
					<view v-if="!item.isShow">
						<!-- <uni-forms-item label="结算类型">
							<view class="item_content"><span style="width: 50%;"><uni-data-select
										@change="changeType(index)" v-model="item.type" :clear="false"
										:localdata="typeList"></uni-data-select></span></view>
						</uni-forms-item> -->
						<uni-forms-item
							required
							:name="['orderFeeDetailVos', index, 'workFeeProjectId']"
							label="费用项目"
							:rules="[{required: true, errorMessage: '费用项目'}]"
						>
							<view class="item_content">
								<span style="width: 80%">
									<uni-data-select
										v-model="item.workFeeProjectId"
										:clear="false"
										:localdata="FeeSeleList"
										@change="(val) => changeFee(val, index)"
									></uni-data-select>
								</span>
							</view>
						</uni-forms-item>
						<uni-forms-item label="申请数量">
							<span class="item_content">
								<uni-number-box :min="1" v-model="item.qty" />
							</span>
						</uni-forms-item>
						<uni-forms-item label="公里数" v-if="item.enableRemoteFees">
							<view class="item_content">
								<span class="input_with_span">
									<uni-easyinput
										class="input_with_"
										type="digit"
										:clearable="false"
										placeholder="0"
										v-model="item.kilometers"
										@input="
											(val) =>
												nextTick(
													() => (item.kilometers = amountForamt(val, 5, 3)),
												)
										"
										@change="changeInputKilometers(index)"
									></uni-easyinput>
								</span>
							</view>
						</uni-forms-item>
						<uni-forms-item label="单价金额" v-if="item.type == 1">
							<view class="item_content" v-if="item.isChangePrice">
								<span class="input_with_span">
									￥
									<uni-easyinput
										class="input_with"
										type="digit"
										:clearable="false"
										placeholder="0.00"
										v-model="item.networkUndertakePrice"
										@input="
											(val) =>
												nextTick(
													() =>
														(item.networkUndertakePrice = amountForamt(
															val,
															8,
															2,
														)),
												)
										"
										@change="changeInput(item)"
									></uni-easyinput>
								</span>
							</view>
							<span class="item_content" v-else>
								￥{{ item.networkUndertakePrice.toFixed(2) }}
							</span>
						</uni-forms-item>
						<uni-forms-item label="单价金额" v-else>
							<view class="item_content" v-if="item.isChangePrice">
								<span class="input_with_span">
									￥
									<uni-easyinput
										class="input_with"
										type="digit"
										:clearable="false"
										placeholder="0.00"
										v-model="item.customerUndertakePrice"
										@input="
											(val) =>
												nextTick(
													() =>
														(item.customerUndertakePrice = amountForamt(
															val,
															8,
															2,
														)),
												)
										"
										@change="changeInput(item)"
									></uni-easyinput>
								</span>
							</view>
							<span class="item_content" v-else>
								￥{{ item.customerUndertakePrice.toFixed(2) }}
							</span>
						</uni-forms-item>
						<uni-forms-item label="总金额" v-if="item.type == 1">
							<span class="item_content" style="font-weight: bold">
								￥{{ (item.networkUndertakePrice * item.qty).toFixed(2) }}
							</span>
						</uni-forms-item>
						<uni-forms-item label="总金额" v-else>
							<span class="item_content" style="font-weight: bold">
								￥{{ (item.customerUndertakePrice * item.qty).toFixed(2) }}
							</span>
						</uni-forms-item>
						<uni-forms-item label="">
							<span style="color: #606266; font-size: 28rpx">备注</span>
							<view class="text_input">
								<uni-easyinput
									type="textarea"
									:inputBorder="false"
									placeholderStyle="font-size:28rpx;"
									:maxlength="100"
									v-model="item.remark"
									placeholder="填写备注"
								></uni-easyinput>
								<view class="coun">{{ item.remark.length }}/100</view>
							</view>
						</uni-forms-item>
						<uni-forms-item
							label=""
							:name="['orderFeeDetailVos', index, 'imgarr']"
						>
							<view class="pic_img">
								<uni-file-picker
									@select="(files) => onsuccessImg(files, index)"
									title="图片"
									limit="8"
									:auto-upload="false"
									@delete="(file) => ondeleteImg(file, index)"
									file-extname="jpg,jpeg,png"
									:imageStyles="imageStyles"
									file-mediatype="image"
									v-model="item.imgarr"
								/>
							</view>
						</uni-forms-item>
					</view>
				</view>
			</uni-forms>
		</view>
		<view class="footer_order">
			<view class="footer_order_left" @click="addFeeItem">
				<uni-icons type="plus-filled" color="#007cff" size="28"></uni-icons>
				<p class="gray_tip">添加费用</p>
			</view>
			<view class="footer_order_right" @click="submitFun">
				<view class="btn">提交申请</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import {ref, onMounted, reactive, watch, nextTick} from 'vue';
	import {onUnload, onShow, onLoad, onHide} from '@dcloudio/uni-app';
	import apiOrder from '@/util/network_api/apiOrder.js';
	import apiUpload from '@/util/network_api/upload.js';
	import _ from 'lodash';
	import {amountForamt} from '@/util/autoInputValue';

	const workId = ref(null); //工单Id
	const formRef = ref();
	onLoad(async (e) => {
		if (!e.workId) return;
		workId.value = e.workId;
		new Promise(() => {
			getOrderServiceFeeSelectList();
		});
	});
	onUnload(() => {
		uni.hideLoading();
	});
	const imageStyles = {
		height: 80, // 边框高度
		width: 80, // 边框宽度
		border: {
			// 如果为 Boolean 值，可以控制边框显示与否
			color: '#eee', // 边框颜色
			width: '1px', // 边框宽度
			style: 'solid', // 边框样式
		},
	};
	// 结算类型
	const typeList = ref([
		{text: '厂家承担费用', value: 1},
		{text: '收取客户费用', value: 2},
	]);

	const orderFeeVo = ref({
		orderFeeDetailVos: [
			{
				isShow: false,
				isChangePrice: false, //
				enableRemoteFees: false, //是否启用公里数
				iamges: [],
				imgarr: [],
				price: 0, //包费用
				kilometers: 0, //公里数
				// payNetworkPrice: 0,
				// receiveFactoryPrice: 0,//商家承担
				customerUndertakePrice: 0,
				networkUndertakePrice: 0,
				qty: 1,
				remark: '',
				type: 1, //结算类型：1-商家承担，2-平台承担,示例值(1)
				workFeeProjectId: null, //	工单费用项目ID
			},
		],
	});
	// ***点击结算类型变化
	const changeType = (index) => {
		if (orderFeeVo.value.orderFeeDetailVos[index].type == 1) {
			orderFeeVo.value.orderFeeDetailVos[index].price =
				orderFeeVo.value.orderFeeDetailVos[index].customerUndertakePrice;
			orderFeeVo.value.orderFeeDetailVos[index].customerUndertakePrice = 0;
		} else if (orderFeeVo.value.orderFeeDetailVos[index].type == 2) {
			orderFeeVo.value.orderFeeDetailVos[index].price =
				orderFeeVo.value.orderFeeDetailVos[index].customerUndertakePrice;
			orderFeeVo.value.orderFeeDetailVos[index].customerUndertakePrice = 0;
		}
	};
	const changeInput = (item) => {
		// if (item.type == 1) {
		// 	item.networkUndertakePrice = item.price
		// } else {
		// 	item.networkUndertakePrice = item.customerUndertakePrice
		// }
	};
	// 公里数变化
	const changeInputKilometers = (index) => {
		let o = orderFeeVo.value.orderFeeDetailVos[index];
		let price = 0;
		if (Number(o.kilometers) > 20) {
			price = parseFloat(((Number(o.kilometers) - 20) * 1.2).toFixed(2));
			if (Number(o.kilometers) > 80) {
				price = 72.0;
				uni
					.showModal({
						title: '提示',
						content: '远程费最多申请72块',
						confirmText: '确定',
						showCancel: false,
					})
					.then((res) => {
						if (res.confirm) {
						}
					});
			}
		}
		o.networkUndertakePrice = price;
	};
	// 获取移动端工单服务费用下拉数据
	const FeeSeleList = ref([]);
	const getOrderServiceFeeSelectList = () => {
		uni.showLoading({
			title: '加载中...',
			mask: true,
		});
		apiOrder.getOrderServiceFeeSelect().then((res) => {
			uni.hideLoading();
			FeeSeleList.value = res.data.rows.map((o) => {
				o['value'] = o.id;
				o['text'] = o.name;
				delete o.id;
				delete o.name;
				return o;
			});
			if (FeeSeleList.value.length == 1) {
				orderFeeVo.value.orderFeeDetailVos[0].workFeeProjectId =
					FeeSeleList.value[0].value;
				changeFee(FeeSeleList.value[0].value, 0);
			}
		});
	};
	const changeFee = (id, index) => {
		FeeSeleList.value.filter((o) => {
			if (o.value == id) {
				if (o.enableRemoteFees) {
					let price = 0;
					if (Number(o.kilometers) > 20) {
						price = parseFloat(((Number(o.kilometers) - 20) * 1.2).toFixed(2));
						if (Number(o.kilometers) > 80) {
							price = 72.0;
							uni
								.showModal({
									title: '提示',
									content: '远程费最高补助公里数上限为80公里',
									confirmText: '确定',
									showCancel: false,
								})
								.then((res) => {
									if (res.confirm) {
									}
								});
						}
					}
					orderFeeVo.value.orderFeeDetailVos[index].networkUndertakePrice =
						price;
				} else {
					if (orderFeeVo.value.orderFeeDetailVos[index].type == 1) {
						orderFeeVo.value.orderFeeDetailVos[index].networkUndertakePrice =
							o.price;
					} else {
						orderFeeVo.value.orderFeeDetailVos[index].customerUndertakePrice =
							o.price;
					}
				}
				// orderFeeVo.value.orderFeeDetailVos[index].networkUndertakePrice = o.price
				orderFeeVo.value.orderFeeDetailVos[index].isChangePrice = o.updatePrice;
				orderFeeVo.value.orderFeeDetailVos[index].enableRemoteFees =
					o.enableRemoteFees;
				orderFeeVo.value.orderFeeDetailVos[index].kilometers = o.kilometers;
			}
		});
	};
	const onsuccessImg = (files, index) => {
		files.tempFiles.map((o) => {
			orderFeeVo.value.orderFeeDetailVos[index].imgarr.push(o);
		});
	};
	const ondeleteImg = (file, index) => {
		orderFeeVo.value.orderFeeDetailVos[index].imgarr =
			orderFeeVo.value.orderFeeDetailVos[index].imgarr.filter((o) => {
				return o.uuid != file.tempFile.uuid;
			});
	};
	// 添加费用
	const addFeeItem = () => {
		let result = orderFeeVo.value.orderFeeDetailVos.every(
			(o) => o.workFeeProjectId,
		);
		let indexShow = orderFeeVo.value.orderFeeDetailVos.some((o) => o.isShow);
		if (!result && indexShow) {
			uni.showToast({
				title: '请先选择费用项目',
				icon: 'none',
			});
			return;
		}
		formRef.value.validate().then(() => {
			orderFeeVo.value.orderFeeDetailVos.push({
				isShow: false,
				isChangePrice: false,
				enableRemoteFees: false, //是否启用公里数
				iamges: [],
				imgarr: [],
				price: 0,
				kilometers: 0, //公里数
				customerUndertakePrice: 0,
				networkUndertakePrice: 0,
				qty: 1,
				remark: '',
				type: 1, //结算类型：1-向商家收取，2-向平台收取,示例值(1)
				workFeeProjectId: null, //	工单费用项目ID
			});
			if (FeeSeleList.value.length == 1) {
				orderFeeVo.value.orderFeeDetailVos[0].workFeeProjectId =
					FeeSeleList.value[0].value;
				changeFee(
					FeeSeleList.value[0].value,
					orderFeeVo.value.orderFeeDetailVos.length - 1,
				);
			}
		});
	};
	// 删除费用
	const deleteFun = (index) => {
		orderFeeVo.value.orderFeeDetailVos.splice(index, 1);
	};
	// 提交
	const submitFun = _.debounce(
		async () => {
			if (!workId.value) return;
			let result = orderFeeVo.value.orderFeeDetailVos.every(
				(o) => o.workFeeProjectId,
			);
			let indexShow = orderFeeVo.value.orderFeeDetailVos.some((o) => o.isShow);
			if (!result && indexShow) {
				uni.showToast({
					title: '请先选择费用项目',
					icon: 'none',
				});
				return;
			}
			await formRef.value
				.validate()
				.then(async (res) => {
					uni.showLoading({
						title: '加载中...',
						mask: true,
					});
					for (let i = 0; i < orderFeeVo.value.orderFeeDetailVos.length; i++) {
						let item = orderFeeVo.value.orderFeeDetailVos[i];
						item.iamges = [];
						if (item.imgarr.length > 0) {
							for (let j = 0; j < item.imgarr.length; j++) {
								let img = item.imgarr[j];
								await apiUpload
									.uploadOrderFile({files: img.file})
									.then((res) => {
										item.iamges.push(res.data.rows[0]);
									});
							}
						}
					}
					let dataObj = _.cloneDeep(orderFeeVo.value);
					dataObj.orderFeeDetailVos = dataObj.orderFeeDetailVos.map((o) => {
						delete o.imgarr;
						delete o.isShow;
						delete o.isChangePrice;
						delete o.enableRemoteFees;
						return o;
					});
					await apiOrder.saveApplyFee(dataObj, workId.value).then((res) => {
						if (res.code == 20000) {
							uni.hideLoading();
							uni.showToast({
								title: '申请服务费',
								icon: 'success',
							});
							uni.setStorageSync('order_detail', 1);
							setTimeout(() => {
								uni.redirectTo({
									url: '/pages_network/order/detail?workId=' + workId.value,
								});
							}, 600);
						}
					});
					uni.hideLoading();
				})
				.catch((err) => {
					uni.showToast({
						title: '请填写完整信息！',
						icon: 'none',
					});
				});
		},
		600,
		{leading: false},
	);
</script>

<style lang="scss" scoped>
	.fee_main {
		/* #ifdef H5 */
		height: calc(100vh - 44px);
		/* #endif */
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */
		width: 100%;
		background: #fafafa;
		display: flex;
		flex-direction: column;
		overflow: auto;

		&::-webkit-scrollbar {
			width: 0;
			height: 0;
			background-color: transparent;
		}

		&_bgBox {
			margin: 24rpx;
			padding-bottom: 220rpx;

			:deep(.uni-forms-item) {
				margin-bottom: 0rpx;
				padding: 10rpx 0;
				border-bottom: 1px solid #eee;
			}

			:deep(.uni-forms-item__label) {
				padding: 0;
				font-size: 28rpx;
			}

			.item_fee {
				background-color: #fff;
				padding: 24rpx;
				margin-bottom: 24rpx;

				:deep(.uni-select) {
					border: none;

					.uni-select__input-placeholder {
						text-align: right;
						margin-right: 12rpx;
						font-size: 28rpx;
						color: #999;
					}

					.uni-select__input-text {
						text-align: right;
						margin-right: 12rpx;
						font-size: 28rpx;
					}

					.uni-popper__arrow {
						left: 70%;
					}

					.uni-select__selector {
						top: 100%;
					}
				}

				&_tableHead {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 24rpx;

					&_left {
						font-size: 28rpx;
						font-weight: bold;
						display: flex;
						align-items: center;

						.down_up {
							width: 0;
							height: 0;
							border-right: 12rpx solid transparent;
							border-left: 12rpx solid transparent;
							border-top: 14rpx solid #000;
							margin-right: 6rpx;
						}

						.down_up_ {
							width: 0;
							height: 0;
							border-right: 12rpx solid transparent;
							border-left: 12rpx solid transparent;
							border-bottom: 14rpx solid #000;
							margin-right: 6rpx;
						}
					}
				}

				.item_content {
					display: flex;
					align-items: center;
					justify-content: flex-end;
					height: 100%;
					margin-left: 24rpx;

					.input_with_span {
						display: flex;
						align-items: center;
					}

					:deep(.input_with) {
						.uni-easyinput__content {
							width: 220rpx !important;
							position: relative;
						}
					}

					:deep(.input_with_) {
						.uni-easyinput__content {
							width: 220rpx !important;
							position: relative;

							&::after {
								position: absolute;
								content: '公里';
								right: 10rpx;
								z-index: 2;
								font-size: 24rpx;
							}
						}
					}
				}

				.text_input {
					margin: 24rpx 0 0 0;
					position: relative;

					:deep(.uni-easyinput__content-textarea) {
						margin: 0;
						// background-color: #fff !important;
					}

					padding: 12rpx 12rpx 24rpx;
					background-color: #fff;
					border: 2rpx solid rgb(243, 244, 248);

					.coun {
						font-size: 26rpx;
						position: absolute;
						right: 12rpx;
						bottom: 6rpx;
						color: #999;
					}
				}

				.pic_img {
					:deep(.uni-file-picker__header) {
						padding-top: 14rpx;
					}

					:deep(.file-title) {
						font-size: 28rpx;
					}

					:deep(.icon-add) {
						width: 30rpx;
						height: 3rpx;
						background-color: #aaa;
					}

					:deep(.icon-del) {
						width: 24rpx;
					}

					:deep(.icon-del-box) {
						width: 40rpx;
						height: 40rpx;
						top: 0;
						right: 0;
						background-color: rgba(0, 0, 0, 0.3);
					}

					:deep(.uni-progress-bar) {
						display: none;
					}
				}
			}
		}

		:deep(.file-picker__progress-item) {
			display: none;
		}

		.footer_order {
			display: flex;
			align-items: center;
			background-color: #ffffff;
			z-index: 99;
			height: 140rpx;
			position: fixed;
			bottom: 0;
			width: 100%;
			padding: 48rpx 48rpx 60rpx;
			box-sizing: border-box;
			border-top: 1px solid #eee;

			&_left {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				font-size: 24rpx;
				margin-right: 24rpx;

				.gray_tip {
					color: #007cff;
				}
			}

			&_right {
				flex: 1;
				border-radius: 45rpx;
				height: 80rpx;
				background-color: #007cff;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #fff;
				font-size: 28rpx;
				font-weight: bold;
			}
		}
	}
</style>
